import { message } from "antd";
import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  AxiosError,
  InternalAxiosRequestConfig, // 引入 InternalAxiosRequestConfig
} from "axios";

// 定义 API 响应结构（根据实际接口调整）
export interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

// 自定义错误类型
export interface ApiError {
  code: number;
  msg: string;
}

class HttpClient {
  private instance: AxiosInstance;

  constructor(baseURL: string, timeout: number = 10000) {
    this.instance = axios.create({
      baseURL,
      timeout,
      headers: { "Content-Type": "application/json","accept":'*/*',"Accept-Encoding":"gzip, deflate, br" },
    });

    this._setupInterceptors();
  }

  // 配置拦截器
  private _setupInterceptors() {
    // 请求拦截器：自动注入 token
    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        // 修改类型为 InternalAxiosRequestConfig
        const token = localStorage.getItem("token");
        if (token && config.headers) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error: AxiosError) => this._handleError(error)
    );

    // 响应拦截器：统一处理错误和业务状态码
    this.instance.interceptors.response.use(
      (response: AxiosResponse<ApiResponse>) => {
        const { code, data, msg } = response.data;
        // 根据业务码处理（示例：200/0 为成功）
        if (code === 200 || code === 0) {
          return response
        } else {
          return Promise.reject({ code, msg } as ApiError);
        }
      },
      (error: AxiosError) => this._handleError(error)
    );
  }

  // 统一错误处理
  private _handleError(error: AxiosError): Promise<ApiError> {
    let errormsg = "请求失败";
    if (error.response) {
      const { status } = error.response;
      // 根据 HTTP 状态码处理
      switch (status) {
        case 400:
          const responseData = error.response.data as ApiResponse<{
            tips: string;
          }>;
          errormsg = `请求参数错误 ${responseData.data.tips}`;
          break;
        case 401:
          errormsg = "登录已过期，请重新登录";
          break;
        case 403:
          errormsg = "权限不足";
          break;
        case 500:
          errormsg = "服务器内部错误";
          break;
        default:
          errormsg = `服务器错误 [${status}]`;
      }
    } else if (error.request) {
      errormsg = "网络连接异常";
    }
    
    // 对于401未授权错误，清除token并跳转到登录页面
    if (error.response && error.response.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('userId');
      localStorage.removeItem('userInfo');
      message.error(errormsg);
      window.location.href = '/login';
    }
    
    return Promise.reject({ code: -1, msg: errormsg });
  }

  // 封装 GET 请求（泛型支持）
  public async get(
    url: string,
    params?: object,
    config?: AxiosRequestConfig
  ): Promise<any> {
    const response = await this.instance.get(url, {
      ...config,
      params,
    });
    return response.data.data;
  }

  // 封装 POST 请求（泛型支持）
  public async post<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<any> {
    const response = await this.instance.post<ApiResponse<T>>(
      url,
      data,
      config
    );
    let resData = response.data  as ApiResponse<T>;
    if (response.data as ApiResponse) {
      message.success(resData.msg);
    } else {
      message.error(resData.msg);
    }
    return response; // 修复：返回实际数据部分
  }
}
const baseURL = import.meta.env.VITE_API_BASE_URL || "";
// const baseURL =""
export const httpClient = new HttpClient(baseURL);
